package com.infore.airsupervise.ui.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.StationExpandAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.bean.StationExpandE;
import com.infore.airsupervise.biz.StatisticsBiz;
import com.infore.airsupervise.biz.impl.StatisticsBizImpl;
import com.infore.airsupervise.http.BaseResponse;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.activity.StationDetailActivity;
import com.infore.airsupervise.utils.JumpUtil;
import com.infore.airsupervise.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 使用recyclerView的公共的站点树fragment
 * Created by xiaotao on 2017/8/12.
 */

public class StationTreeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, StationExpandAdapter.OnItemClickListener {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.swipe_layout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.iv_searchClean)
    ImageView ivSearchClean;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.layout_confirm)
    LinearLayout layoutConfirm;

    private StatisticsBiz statisticsBiz = null;

    private StationExpandAdapter adapter = null;
    private List<MultiItemEntity> stationList = null; // 列表集合
    private List<StationExpandE> totalList = null; // 全部站点列表集合
    private List<StationExpandE> matchList = null; // 匹配的站点列表集合

    private StringBuffer arrayMn;
    private boolean stationSelected;
    private int curType ;

    private OnClickListener onClickListener;



    public interface OnClickListener{
        void onConfirmClick(String  mn);
        void onConfirmClick(String mn , String name);
        void onCancelClick();
    }

    public void setOnClickListener( OnClickListener onClickListener){
        this.onClickListener = onClickListener;
    }

    /**
     * 站点是否可以复选
     * @param enable
     */
    public void setStationTreeSelected(boolean enable) {
        stationSelected = enable;
    }

    public void setCurType(int curType) {
        this.curType = curType;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_station_tree, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    /**
     * 初始化控件
     */
    private void initView() {
        // 设置swipeLayout
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(Color.rgb(52, 152, 219), Color.rgb(231, 76, 60), Color.rgb(46, 204, 113));
        //搜索栏
        tvSearch.setText("搜索");
        //recyclerView
        stationList = new ArrayList<>();
        totalList = new ArrayList<>();
        matchList = new ArrayList<>();
        adapter = new StationExpandAdapter(stationList);
        adapter.setCurType(curType);
        if(curType == StationExpandAdapter.NO_SELECTE){
            adapter.setOnItemClickListener(this);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);
        //底部布局
        layoutConfirm.setVisibility(curType != StationExpandAdapter.NO_SELECTE ? View.VISIBLE : View.GONE);
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(true);
                getStationTree();
            }
        });

    }

    /**
     * 获取选中的站点mn号
     */
    private void   getMnList(){
        StringBuffer arrayMn = new StringBuffer();
        List<String> mnList = adapter.getSelectorPosition();
        if(mnList == null || mnList.size()<=0){
            ToastUtil.showShort(getContext(),"还没有选择站点！");
            return ;
        }
        if(mnList.size()>10){
            ToastUtil.showLong(getContext(), "最多选择10个站点");
            return ;
        }
        for(String mn : mnList){
            arrayMn.append(mn+",");
        }
        onClickListener.onConfirmClick(arrayMn.toString());
    }

    /**
     * 获取单选选项
     */
    private void  getSelecteItem(){
        MultiItemEntity item = adapter.getSelectorItem() ;
        if(item == null){
            ToastUtil.showShort(getContext(),"还没有选择站点！");
            return ;
        }
       switch (item.getItemType()){
           case 0 :
               StationExpandE stationF = (StationExpandE) item;
               onClickListener.onConfirmClick(stationF.getMn(),stationF.getName());
               break;
           case 1 :
               StationExpandE.Station2 stationS = (StationExpandE.Station2) item;
               onClickListener.onConfirmClick(stationS.getMn(),stationS.getName());
               break;
           case 2 :
               StationExpandE.Station3 stationT = (StationExpandE.Station3) item;
               onClickListener.onConfirmClick(stationT.getMn(),stationT.getName());
               break;
       }

    }

    /**
     * 获取站点树
     */
    private void getStationTree() {
        if (statisticsBiz == null) {
            statisticsBiz = new StatisticsBizImpl();
        }
        Call<BaseResponse> call = statisticsBiz.sendStationTreeRequest(requestListener);
        requests.add(call);
    }

    /**
     * 请求回调处理
     */
    private OnServerResponseListener<List<StationExpandE>> requestListener = new OnServerResponseListener<List<StationExpandE>>() {
        @Override
        public void onSucceed(List<StationExpandE> result, String desc) {
            swipeLayout.setRefreshing(false);
            adapter.getData().clear();
            if (result != null) {
                for (StationExpandE station : result) {
                    if (station.getStationList() != null && station.getStationList().size() > 0) {
                        for (StationExpandE.Station2 station2 : station.getStationList()) {
                            if (station2.getStationList() != null && station2.getStationList().size() > 0) {
                                for (StationExpandE.Station3 station3 : station2.getStationList()) {
                                    station2.addSubItem(station3);
                                }
                            }
                            station.addSubItem(station2);
                        }
                    }
                    stationList.add(station);
                }
            }
            totalList.clear();
            totalList.addAll(result);
            recyclerView.scrollToPosition(0);
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onFailed(int errorCode, String title, String desc) {
            swipeLayout.setRefreshing(false);
        }
    };


    @OnClick({R.id.iv_searchClean, R.id.tv_search ,R.id.btn_confirm, R.id.btn_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_searchClean:
                //清空编辑框
                    etSearch.getText().clear();
                    //还原全部站点
                    resetExpandStationList(false);
                    resetExpandStationList(true);
                    stationList.clear();
                    stationList.addAll(totalList);
                    adapter.notifyDataSetChanged();


                break;
            case R.id.tv_search:
                stationSearch();

                break;
            case R.id.btn_confirm:
                if(onClickListener != null){
                    if(curType ==  StationExpandAdapter.CB_SELECTE) {
                        getMnList();
                    }
                    if(curType == StationExpandAdapter.RB_SELECTE){
                        getSelecteItem();
                    }
                }
                break;
            case R.id.btn_cancel:

                if(onClickListener != null){
                    onClickListener.onCancelClick();
                }
        }
    }

    /**
     * 站点树处于可点击状态时 的点击事件
     * @param itemType
     * @param item
     */
    @Override
    public void onClick(int itemType, MultiItemEntity item) {

        switch (itemType){
            case 0 :
                StationExpandE stationF = (StationExpandE) item;
                JumpUtil.jumpFromTo(getContext(), StationDetailActivity.class, Constants.INTENT_STR_KEY,stationF.getMn());
                break;
            case 1 :
                StationExpandE.Station2 stationS = (StationExpandE.Station2) item;
                JumpUtil.jumpFromTo(getContext(), StationDetailActivity.class, Constants.INTENT_STR_KEY,stationS.getMn());
                break;
            case 2:
                StationExpandE.Station3 stationT = (StationExpandE.Station3) item;
                JumpUtil.jumpFromTo(getContext(), StationDetailActivity.class, Constants.INTENT_STR_KEY,stationT.getMn());
                break;

        }
    }

    @Override
    public void onRefresh() {
        getStationTree();
    }


    private boolean flag1 ;
    private boolean flag2;
    private void stationSearch(){
        stationList.clear();
        String key = etSearch.getText().toString();
        if(TextUtils.isEmpty(key.trim())){
            ToastUtil.showLong(getContext(),"请输入搜索内容");
            return ;
        }
        //先清空集合内的可扩展选项
        resetExpandStationList(false);

        for(StationExpandE station1 : totalList){
            if(station1.getName().toLowerCase().contains(key.toLowerCase())){ // 第一层 匹配了 则下面的所有子节点都添加
                if(station1.getStationList() != null && station1.getStationList().size()>0){
                    for(StationExpandE.Station2 station2 : station1.getStationList()){
                        if (station2.getStationList() != null && station2.getStationList().size() > 0) {
                    for (StationExpandE.Station3 station3 : station2.getStationList()) {
                            station2.addSubItem(station3);
                    }
                }
                        station1.addSubItem(station2);
                    }
                }
                stationList.add(station1);
            }else { // 不匹配则进入子节点
                if(station1.getStationList() != null && station1.getStationList().size()>0){
                    flag1 = false ;
                    for(StationExpandE.Station2 station2 : station1.getStationList()){
                       flag2 = false ;
                        if(station2.getName().toLowerCase().contains(key.toLowerCase())){
                            flag1 = true;
                            //第二层 匹配了 则下面的所有子节点都添加
                            if (station2.getStationList() != null && station2.getStationList().size() > 0) {
                                for (StationExpandE.Station3 station3 : station2.getStationList()) {
                                    station2.addSubItem(station3);
                                }
                            }
                            station1.addSubItem(station2);
                        }else {
                            // 不匹配则进入子节点
                            if(station2.getStationList() != null && station2.getStationList().size() > 0){
                                for(StationExpandE.Station3 station3 : station2.getStationList()){
                                    if(station3.getName().toLowerCase().contains(key.toLowerCase())){
                                        flag2 = true;
                                        flag1 = true ;
                                        station2.addSubItem(station3);
                                    }
                                }
                            }
                            if(flag2){
                                station1.addSubItem(station2);
                            }
                        }

                    }
                    if(flag1){
                        stationList.add(station1);
                    }
                }
            }
        }
        adapter.notifyDataSetChanged();
    }


    /**
     *
     * 重置 站点列表的展开状态
     */
    private void resetExpandStationList(boolean isAdd){
        for (StationExpandE station : totalList) {
            if (station.getStationList() != null && station.getStationList().size() > 0) {
                for (StationExpandE.Station2 station2 : station.getStationList()) {
                    if (station2.getStationList() != null && station2.getStationList().size() > 0) {
                        for (StationExpandE.Station3 station3 : station2.getStationList()) {
                            if(!isAdd) {
                                station2.removeSubItem(station3);
                            }else {
                                station2.addSubItem(station3);
                            }
                        }
                    }
                    if(!isAdd) {
                        station.removeSubItem(station2);
                    }else {
                        station.addSubItem(station2);
                    }
                }
            }
        }
    }
}
